package com.example.demoweb1;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@SpringBootApplication
@RestController
@RequestMapping("/app1")
public class DemoWeb1Application {

    public static void main(String[] args) {
        SpringApplication.run(DemoWeb1Application.class, args);
    }

    @RequestMapping("/mapping1")
    public void mapping1(HttpServletRequest request, HttpServletResponse response){
        System.out.println("mapping1 called,parameter A : " + request.getParameter("A"));

        Cookie cookie = new Cookie("cookie1","cookie1_val");
        cookie.setMaxAge(Integer.MAX_VALUE);
        response.addCookie(cookie);

        try {
            response.sendRedirect("/app1/mapping2");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @RequestMapping("/mapping2")
    public void mapping2(HttpServletRequest request, HttpServletResponse response,
                         @CookieValue(value = "cookie3")String cookie3)
    {
        Cookie[] cookies = request.getCookies();
        for (int i = 0; i < cookies.length; i++) {
            Cookie c = cookies[i];
            System.out.println(c.getName()+":"+c.getValue());
        }

        System.out.println("cookie3 : "+cookie3);
    }

    @InitBinder
    public void init(){
        System.out.println("Application initialized");
    }

}
